<?php
/*******************************************
	Website static and dynamic content
*******************************************/

// Avoid direct access
if(substr_count($_SERVER['PHP_SELF'], 'content.php') > 0) {
	header("HTTP/1.0 404 Not Found");
	exit;
}

// requires: THEY ARE ALREADY INSIDE THE CONFIG FILE
	// a language class file -> the parent class
	// pagination.php -> pagination class

class Content extends Language{	


	/* Get the requested page */
	public static function get_page($request) {
		
		if(substr_count($request, "/") > 0) {
			$tmp = explode("/", $request);
			if(is_array($tmp) && (count($tmp) > 1)) {
				return strtolower(array_pop($tmp));
			}
			return false;
		}
		
		return $request;
	}
	
	/* retrieve the main menu */
	public static function get_main_menu($page = "home", $isLogged = false) {
		
		$sess = "";
		$saved_searches = "";
		if($isLogged) {
			$sess = "?".htmlspecialchars(SID);
		}
		
		
		$login_logout = '<li><a title="'.self::MENU_LOGIN.'" href="login">'.self::MENU_LOGIN.'</a> |</li>
						 <li><a title="'.self::MENU_CREATE_ACCOUNT.'" href="register">'.self::MENU_CREATE_ACCOUNT.'</a> ||</li>';
		if($page == "login") {
			$login_logout = '<li class="selected">'.self::MENU_LOGIN.' |</li>
							 <li><a title="'.self::MENU_CREATE_ACCOUNT.'" href="register">'.self::MENU_CREATE_ACCOUNT.'</a> ||</li>';
		} else if ($page == "register") {
			$login_logout = '<li><a title="'.self::MENU_LOGIN.'" href="login">'.self::MENU_LOGIN.'</a> |</li>
							 <li class="selected">'.self::MENU_CREATE_ACCOUNT.' ||</li>';
		}
		if($isLogged) {
			$login_logout = '<li><a title="'.self::MENU_LOGOUT.'" href="logout'.$sess.'">'.self::MENU_LOGOUT.'</a> |</li>
							 <li><a title="'.self::MENU_PROFILE.'" href="profile'.$sess.'">'.self::MENU_PROFILE.'</a> ||</li>';
			$saved_searches = '<li> || <a title="'.self::MENU_SAVED_SEARCHES.'" href="saved-searches'.$sess.'">'.self::MENU_SAVED_SEARCHES.'</a></li>';
			if($page == "logout") {
				$login_logout = '<li>'.self::MENU_LOGOUT.'</li>
								 <li><a title="'.self::MENU_PROFILE.'" href="profile'.$sess.'">'.self::MENU_PROFILE.'</a> ||</li>';
			} else if($page == "profile") {
				$login_logout = '<li><a title="'.self::MENU_LOGOUT.'" href="logout'.$sess.'">'.self::MENU_LOGOUT.'</a> |</li>
							 	 <li class="selected">'.self::MENU_PROFILE.' ||</li>';
			} else if($page == "saved-searches") {
				$saved_searches = '<li class="selected"> || <a title="'.self::MENU_SAVED_SEARCHES.'" href="saved-searches'.$sess.'">'.self::MENU_SAVED_SEARCHES.'</a></li>';
			}
		}
		
		$menu = '<li><a title="'.self::MENU_HOME.'" href="home'.$sess.'">'.self::MENU_HOME.'</a> |</li>
				<li><a title="'.self::MENU_ABOUT.'" href="about'.$sess.'">'.self::MENU_ABOUT.'</a> | </li>
				<li><a title="'.self::MENU_COLLECTIONS.'" href="collections'.$sess.'">'.self::MENU_COLLECTIONS.'</a> |</li>
				<li><a title="'.self::MENU_CONTACT_US.'" href="contact'.$sess.'">'.self::MENU_CONTACT.'</a> ||</li>
				'.$login_logout;
				
		
		switch($page) {
			case "home":
				$menu = '<li class="selected">'.self::MENU_HOME.' |</li>
						<li><a title="'.self::MENU_ABOUT.'" href="about'.$sess.'">'.self::MENU_ABOUT.'</a> |</li>
						<li><a title="'.self::MENU_COLLECTIONS.'" href="collections'.$sess.'">'.self::MENU_COLLECTIONS.'</a> |</li>
						<li><a title="'.self::MENU_CONTACT_US.'" href="contact'.$sess.'">'.self::MENU_CONTACT.'</a> ||</li>
						'.$login_logout.'
						<li><a title="'.self::MENU_SEARCH_TITLE.'" href="search'.$sess.'">'.self::MENU_SEARCH.'</a></li>
						'.$saved_searches;		
				break;
			case "about":
				$menu = '<li><a title="'.self::MENU_HOME.'" href="home'.$sess.'">'.self::MENU_HOME.'</a> |</li>
						<li class="selected">'.self::MENU_ABOUT.' |</li>
						<li><a title="'.self::MENU_COLLECTIONS.'" href="collections'.$sess.'">'.self::MENU_COLLECTIONS.'</a> |</li>
						<li><a title="'.self::MENU_CONTACT_US.'" href="contact'.$sess.'">'.self::MENU_CONTACT.'</a> ||</li>
						'.$login_logout.'
						<li><a title="'.self::MENU_SEARCH_TITLE.'" href="search'.$sess.'">'.self::MENU_SEARCH.'</a></li>
						'.$saved_searches;
				break;
			case "collections":
				$menu = '<li><a title="'.self::MENU_HOME.'" href="home'.$sess.'">'.self::MENU_HOME.'</a> |</li>
						<li><a title="'.self::MENU_ABOUT.'" href="about'.$sess.'">'.self::MENU_ABOUT.'</a> |</li>
						<li class="selected">'.self::MENU_COLLECTIONS.' |</li>
						<li><a title="'.self::MENU_CONTACT_US.'" href="contact'.$sess.'">'.self::MENU_CONTACT.'</a> ||</li>
						'.$login_logout.'
						<li><a title="'.self::MENU_SEARCH_TITLE.'" href="search'.$sess.'">'.self::MENU_SEARCH.'</a></li>
						'.$saved_searches;		
				break;
			case "contact":
				$menu = '<li><a title="'.self::MENU_HOME.'" href="home'.$sess.'">'.self::MENU_HOME.'</a> |</li>
						<li><a title="'.self::MENU_ABOUT.'" href="about'.$sess.'">'.self::MENU_ABOUT.'</a> |</li>
						<li><a title="'.self::MENU_COLLECTIONS.'" href="collections'.$sess.'">'.self::MENU_COLLECTIONS.'</a> |</li>
						<li class="selected">'.self::MENU_CONTACT.' ||</li>
						'.$login_logout.'
						<li><a title="'.self::MENU_SEARCH_TITLE.'" href="search'.$sess.'">'.self::MENU_SEARCH.'</a></li>
						'.$saved_searches;
				break;
			case "search":
				$menu = '<li><a title="'.self::MENU_HOME.'" href="home'.$sess.'">'.self::MENU_HOME.'</a> |</li>
						<li><a title="'.self::MENU_ABOUT.'" href="about'.$sess.'">'.self::MENU_ABOUT.'</a> |</li>
						<li><a title="'.self::MENU_COLLECTIONS.'" href="collections'.$sess.'">'.self::MENU_COLLECTIONS.'</a> |</li>
						<li><a title="'.self::MENU_CONTACT_US.'" href="contact'.$sess.'">'.self::MENU_CONTACT.'</a> ||</li>
						'.$login_logout.'
						<li class="selected">'.self::MENU_SEARCH.'</li>
						'.$saved_searches;
				break;
			case "login":case "logout":
				$menu = '<li><a title="'.self::MENU_HOME.'" href="home'.$sess.'">'.self::MENU_HOME.'</a> |</li>
						<li><a title="'.self::MENU_ABOUT.'" href="about'.$sess.'">'.self::MENU_ABOUT.'</a> |</li>
						<li><a title="'.self::MENU_COLLECTIONS.'" href="collections'.$sess.'">'.self::MENU_COLLECTIONS.'</a> |</li>
						<li><a title="'.self::MENU_CONTACT_US.'" href="contact'.$sess.'">'.self::MENU_CONTACT.'</a> ||</li>
						'.$login_logout.'
						<li><a title="'.self::MENU_SEARCH_TITLE.'" href="search'.$sess.'">'.self::MENU_SEARCH.'</a></li>
						'.$saved_searches;
				break;
										
			default:
				$menu = '<li><a title="'.self::MENU_HOME.'" href="home'.$sess.'">'.self::MENU_HOME.'</a> |</li>
						<li><a title="'.self::MENU_ABOUT.'" href="about'.$sess.'">'.self::MENU_ABOUT.'</a> |</li>
						<li><a title="'.self::MENU_COLLECTIONS.'" href="collections'.$sess.'">'.self::MENU_COLLECTIONS.'</a> |</li>
						<li><a title="'.self::MENU_CONTACT_US.'" href="contact'.$sess.'">'.self::MENU_CONTACT.'</a> ||</li>
						'.$login_logout.'
						<li><a title="'.self::MENU_SEARCH_TITLE.'" href="search'.$sess.'">'.self::MENU_SEARCH.'</a></li>
						'.$saved_searches;			
				break;
		}
		return $menu;
	}
	
	/* Get submenus for images	 */
	public static function get_image_submenu($id, $tab, $isLogged = false) {
	
		$id = (int)$id;	// prevent hacking
		$menu = '';
		
		$sess = "";
		$comm_sess = "";
		if($isLogged) {
			$sess = "&".htmlspecialchars(SID);
			$comm_sess = $sess;
		} /*else {
			// captcha code
			$key = Captcha::createCode(8);
			$word = Captcha::createCode(4);
			$encoded = Captcha::Crypt($word, $key); 
			$comm_sess = "&session=".$encoded.$key;
		}	*/
		
		if(isset($_GET['s'])) {
			$sess .= "&s=".$_GET['s'];
		}
		if(isset($_GET['order'])) {
			$sess .= "&order=".$_GET['order'];
		}
		
		switch($tab) {
			case "main":default:	// main page
				$menu = '<div id="submenu"> 
							<ul class="menu"> 
								<li><a title="'.self::MENU_MORE_INFO.'" href="view?image='.$id.'&tab=info'.$sess.'">'.self::MENU_MORE.'</a> |</li> 
								<li><a title="'.self::MENU_COMMENTS.'" href="view?image='.$id.'&tab=comments'.$comm_sess.'">'.self::MENU_COMMENTS.'</a> |</li> 
								<li><a title="'.self::MENU_RELATED_IMAGES.'" href="view?image='.$id.'&tab=related-images'.$comm_sess.'">'.self::MENU_RELATED_IMAGES.'</a></li> 
							</ul>					
						</div> ';
				break;
				
			case "info":
				$menu = '<div id="submenu"> 
							<ul class="menu"> 
								<li><a title="'.self::MENU_VIEW_IMAGE.'" href="view?image='.$id.'&tab=main'.$sess.'">'.self::MENU_IMAGE.'</a> |</li> 
								<li><a title="'.self::MENU_COMMENTS.'" href="view?image='.$id.'&tab=comments'.$comm_sess.'">'.self::MENU_COMMENTS.'</a> |</li> 
								<li><a title="'.self::MENU_RELATED_IMAGES.'" href="view?image='.$id.'&tab=related-images'.$comm_sess.'">'.self::MENU_RELATED_IMAGES.'</a></li> 
							</ul>					
						</div> ';
				break;
							
				break;
				
			case "comments":
				$menu = '<div id="submenu"> 
							<ul class="menu"> 
								<li><a title="'.self::MENU_VIEW_IMAGE.'" href="view?image='.$id.'&tab=main'.$sess.'">'.self::MENU_IMAGE.'</a> |</li> 
								<li><a title="'.self::MENU_MORE_INFO.'" href="view?image='.$id.'&tab=info'.$sess.'">'.self::MENU_MORE.'</a> |</li> 
								<li><a title="'.self::MENU_RELATED_IMAGES.'" href="view?image='.$id.'&tab=related-images'.$comm_sess.'">'.self::MENU_RELATED_IMAGES.'</a></li> 
							</ul>					
						</div> ';			
				break;
				
			case "add-comment":
				$menu = '<div id="submenu"> 
							<ul class="menu"> 
								<li><a title="'.self::MENU_VIEW_IMAGE.'" href="view?image='.$id.'&tab=main'.$sess.'">'.self::MENU_IMAGE.'</a> |</li> 
								<li><a title="'.self::MENU_MORE_INFO.'" href="view?image='.$id.'&tab=info'.$sess.'">'.self::MENU_MORE.'</a> |</li> 
								<li><a title="'.self::MENU_COMMENTS.'" href="view?image='.$id.'&tab=comments'.$comm_sess.'">'.self::MENU_COMMENTS.'</a> |</li> 
								<li><a title="'.self::MENU_RELATED_IMAGES.'" href="view?image='.$id.'&tab=related-images'.$sess.'">'.self::MENU_RELATED_IMAGES.'</a></li> 	
							</ul>					
						</div> ';	
									
				break;
				
			case "related-images":
				$menu = '<div id="submenu"> 
							<ul class="menu"> 
								<li><a title="'.self::MENU_VIEW_IMAGE.'" href="view?image='.$id.'&tab=main'.$sess.'">'.self::MENU_IMAGE.'</a> |</li> 
								<li><a title="'.self::MENU_MORE_INFO.'" href="view?image='.$id.'&tab=info'.$sess.'">'.self::MENU_MORE.'</a> |</li> 
								<li><a title="'.self::MENU_COMMENTS.'" href="view?image='.$id.'&tab=comments'.$comm_sess.'">'.self::MENU_COMMENTS.'</a></li> 
							</ul>					
						</div> ';			
				break;
	
			case "related-image":
				$menu = '<div id="submenu"> 
							<ul class="menu"> 
								<li><a title="'.self::MENU_VIEW_IMAGE.'" href="view?image='.$id.'&tab=main'.$sess.'">'.self::MENU_IMAGE.'</a> |</li> 
								<li><a title="'.self::MENU_MORE_INFO.'" href="view?image='.$id.'&tab=info'.$sess.'">'.self::MENU_MORE.'</a> |</li> 
								<li><a title="'.self::MENU_COMMENTS.'" href="view?image='.$id.'&tab=comments'.$comm_sess.'">'.self::MENU_COMMENTS.'</a> |</li> 
								<li><a title="'.self::MENU_RELATED_IMAGES.'" href="view?image='.$id.'&tab=related-images'.$sess.'">'.self::MENU_RELATED_IMAGES.'</a></li> 
							</ul>					
						</div> ';			
				break;
	
		}


		return $menu;
	}
	
	/* retrieve the breadcrumb navigation (if any) */
	public static function get_breadcrumb($page = "home", array $items = null, $isLogged = false) {
		
		$sess = "";
		if($isLogged) {
			$sess = "?".htmlspecialchars(SID);
		}		
		
		$breadcrumb = '';
		
		switch($page) {
			case "home": case "about": case "collections": case "contact": default:
				$breadcrumb = '';				
				break;
				
			case "view": case "collection": case "browse-collection": case "collection-info":
				$breadcrumb = '<ul class="breadcrumbs">';
				
				foreach($items as $title => $link) {
					if(!is_null($link) ) {
					
						// session
						if(substr_count($link, "?") > 0) {
							$sess = str_replace("?", "&", $sess);
						}
					
						$breadcrumb .= 	"<li><a title='$title' href='$link$sess'>$title</a> &gt; </li>";
					} else {
						$breadcrumb .= 	"<li>$title</li>";
					}
					
				}
							
				$breadcrumb .= 	'</ul>';
				break;	
		}
		return $breadcrumb;
	}	
	

	/* Pagination */
	public static function get_pagination($page, $start, $items, $limit) {
		
		// PAGINATION CLASS INIT
		$p = new pagination;
		$p->items($items);
		$p->limit($limit); // Limit entries per page
		$p->target(str_replace("&","&amp;",$page));
		$p->currentPage($start); // Gets and validates the current page
		//$p->calculate(); // Calculates what to show
		$p->parameterName('s');
		$p->adjacents(2); //No. of page away from the current page
		
		
		
		
		$p->prevT = "";
		$p->nextT = "";
		$p->displaying = "Displaying";
		$p->of = "of";
		
		return $p->getOutput();
	}	
	
	
	/* get the content of a page */
	public static function get_static_content($content, array $variables = null) {
	
		// add error
		if(!is_null($variables)) {
		
			foreach($variables as $key => $value) {
				$content = str_replace(LEFT_SEPARATOR.strtoupper($key).RIGHT_SEPARATOR, $value, $content);
			}

		}
		
		return $content;
	}
	
	/* Retrieve the content of a html page */
	public static function get_dynamic_content($url, $cleanIt = true) {
		
		$ch = parent::init();
		
		
		curl_setopt ($ch, CURLOPT_URL, $url);
		$content = curl_exec($ch);
		
		if(curl_getinfo($ch,CURLINFO_HTTP_CODE) != 200) {
			return false;
		} 
		
		// check if we have a mobile version of the text (headline)
		if(substr_count($content, "<!--headline-->") > 0) {
			$content = substr($content, 0, strrpos($content, "<!--headline-->"));
			$content = str_replace("<!--headline-->", "", $content);
			$content = str_replace('<p></p>', "", $content);
		}
		
		if($cleanIt) {
	
			if(substr_count("<!--", $content) > 0) {
				$tmp = explode("<!--", $content);
				$content = $tmp[0];
			}
			$content = str_replace('<h2> <span class="mw-headline">', '<h3>', $content);
			$content = str_replace('</span></h2>', '</h3>', $content);
			$content = str_replace('<h2>', '<h3>', $content);
			$content = str_replace('</h2>', '</h3>', $content);
			$content = preg_replace("/<img[^>]+\>/i", "", $content);
		}
		
		return $content;
	}	
	
	/* get all the collections */
	public static function get_collections($collection_id = null) {
		
		$ch = parent::init();
		
		curl_setopt ($ch, CURLOPT_URL, HTTP."/cgi/c?output=XML");
		$result = curl_exec($ch);
		
		// There is a bug in EPRint
		// TEMPORARY FIX from here
		$result = str_ireplace('h2 xmlns=', 'collections_header xmlns=', $result);
		$result = str_ireplace('</h2></h2>', '</h2></collections_header>', $result);
		
		$xml = new SimpleXMLElement(trim($result));	

		if($xml !== false) {
			
			$collections = array();
			
			$header = "";
			$intro = "";
			
			foreach ($xml->children() as $key => $value) {
				
				// Header
				if($key == "collections_header") {
				
					$header = str_replace('<collections_header xmlns="http://www.w3.org/1999/xhtml">', "", $value->asXML());
					$header = str_replace('</collections_header>', "", $header);
					$header = str_replace('h2', "h3", $header);

				}
				
				// Introduction
				if($key == "collections_text") {
				
					$intro = str_replace('<collections_text xmlns="http://www.w3.org/1999/xhtml">', "", $value->asXML());
					$intro = str_replace('</collections_text>', "", $intro);

				}
				
				
				if($key == "collections_list") {
					
					foreach($value->children() as $items) {
						
						$item = $items->children();
						
						$image = array();
						foreach($item[0]->children() as $img_attr) {
							$attr = $img_attr->attributes();
							
							$image = array(
											"src"		=> (string)$attr["src"],
											"alt"		=> (string)$attr["alt"],
											"width"		=> (string)$attr["width"],
											"height"	=> (string)$attr["height"]
							);							
						}
						
						// get region and ethnic group lists
						$ethnic_group = array();
						foreach($item[4]->children() as $select_key => $select_value) {
							if((string)$select_key == "values") {
								foreach($select_value->children() as $option) {
									array_push($ethnic_group, (string)$option);
								}
							}
						}
						$region = array();
						foreach($item[5]->children() as $select_key => $select_value) {
							if((string)$select_key == "values") {
								foreach($select_value->children() as $option) {
									array_push($region, (string)$option);
								}
							}
						}						
						
						$collection = array(
												"intro"			=> $header.$intro."<br />",
												"id"			=> (string)$item[2],
												"title"			=> (string)$item[1],
												"description"	=> (string)$item[3]->asXML(),
												"image"			=> $image,
												"ethnic_group"	=> $ethnic_group,
												"region"		=> $region
						);
						
						// in case only one collection is required
						if(!is_null($collection_id) && ($collection["id"] == $collection_id) && ($collection["title"] != "")) return $collection;
							
						if($collection["title"] != "") array_push($collections, $collection);
		
					}
					
				}
				
			}			
			
			if(!is_null($collection_id)) return false;
			
			return $collections;
		
		}

		return false;
	
	}
	
	
	/* get collection items */
	public static function get_collection_items($id) {
	
		// get menu content
		$content = self::get_dynamic_content(WIKI."/index.php/{$id}_menu?action=render");
	
		// if found the menu: clean it
		if(substr_count($content, "<ul>") > 0) {
			
			$xml = new SimpleXMLElement(trim($content));
		
			// get menu links
			$links = $xml->xpath("//ul/li/a");
			
			if(count($links) > 0) {
			
				$items = array();
				
				foreach($links as $link) {
						
					$attr = $link->attributes();
					$items[(string)$link] = str_replace("/cgi/c/$id/", "", (string)$attr[0]);

				}

				return $items;
			
			}
			
			
		}
		
		
		return false;

	
	}
	
	/* get collection submenu */
	public static function get_collection_submenu(array $items, $current_item_id, $collection_id, $isLogged = false) {
	
		$sess = "";
		if($isLogged) {
			$sess = "?".htmlspecialchars(SID);
		}		
		
		$menu = '<ul class="breadcrumbs">';
		
		foreach($items as $title => $link) {
		
			if($link != $current_item_id ) {
			
				$link = "collection-info?collection=$collection_id&tab=".$link;
			
				// session
				if(substr_count($link, "?") > 0) {
					$sess = str_replace("?", "&", $sess);
				}
			
				$menu .= 	"<li><a title='$title' href='$link$sess'>$title</a> | </li>";
			} else {
				$menu .= 	"<li>$title | </li>";
			}
			
		}
					
		$menu .= 	'</ul>';

		return $menu;		
	
	} 
	
	
	/* get info about a collection */
	public static function get_collection_info($item) {
	
		// prepare url
		$url = WIKI."/index.php/".rawurlencode($item)."?redirect=no&action=render";

		// make request
		$content = self::get_dynamic_content($url, false);
		
		// check if any REDIRECT
		if(substr_count($content, "redirectText") > 0) {
			// find the redirect
			preg_match('#href=[\'"]([^\'"]+)[\'"]#i', $content, $matches);
		
			if(count($matches) > 0) {
			
				$tmp = print_r($matches[1], true);
				$url = $tmp."?redirect=no&action=render";
				
				// make request
				$content = self::get_dynamic_content($url, false);
				
				
			}
		}

		// clean content
		$content = self::clean_content($content);

		return $content;
	
	} 
	
	
	/* Make content ready for mobile */
	public static function clean_content($content) {
	
		// images
		/*$content = preg_replace("/<img /i", "<br /><img class=\"captioned\" ", $content);
		$content = preg_replace("/width=\"+[0-9]+\"/i", " ", $content);
		$content = preg_replace("/height=\"+[0-9]+\"/i", " ", $content);*/
		
		$content = preg_replace(array("/<img /i","/width=\"+[0-9]+\"/i", "/height=\"+[0-9]+\"/i"), array("<br /><img class=\"captioned\" ", "", ""), $content);
		
		$content = str_ireplace("src=\"http", "src=\"".Image::SRC."x80/http", $content);
		$content = str_ireplace("src=\"/", "src=\"".Image::SRC."x80/".HTTP."/", $content);
		
		// bold
		$content = str_ireplace("<b>", "<strong>", $content);
		$content = str_ireplace("</b>", "</strong>", $content);
		
		// title
		$content = str_replace('<h2> <span class="mw-headline">', '<h3>', $content);
		$content = str_replace('</span></h2>', '</h3>', $content);
		
		// links
		$content = preg_replace("/<a[^>]+>/i", "", $content);
		$content = str_replace('<a>', '</a>', $content);
		
		return $content;
	}
	
	/* browse a collection */
	public static function browse_collection($collection_id, $offset=0, $limit=5, $order = null) {
	
		return self::simple_search(null, $collection_id, $offset, $limit, true, $order);
	
	}
	
	
	
	/* 	get single image data */
	public static function get_image($id) {
	
		$id = (int)$id;	// prevent hacking
		
		$ch = parent::init();
		
		curl_setopt ($ch, CURLOPT_URL, HTTP."/cgi/export/$id/XML");
		$result = curl_exec($ch);
		
		$xml = new SimpleXMLElement(trim($result));
		
		$attr = $xml->attributes();
		if( (count($attr) > 0) && ($attr["id"] == HTTP."/id/eprint/$id") ) {	// item [image] found
		
			// I need the preview image
			if( ($image = self::search_by_id($id)) !== false ) {
		
				// title, img, thumb are the same
				$item = $image;
				
				// other data
				
				// BASIC INFO
				// Description
				$item["description"] = (string)$xml->abstract; 				
				
				// Location
				$item["location"] = (string)$xml->location;
				if(array_key_exists("state_province", $xml)) {
					$item["location"] .= ", ".(string)$xml->state_province;
				} 
				if(array_key_exists("country", $xml)) {
					$item["location"] .= ", ".(string)$xml->country;
				} 					
				
				if(array_key_exists("date", $xml)) {
					$item["date"] = date('d F Y', strtotime((string)$xml->date));
				}
				
				

				// EXTRA INFO
				$item["extra"] = array();
				
				// NOW WITH A GENERIC FOREACH
				// I need anyway to EXCLUDE some of them
				
	// check 
				//	copyright_holders
				//	documents	
				// Date fields
				// Empty fields	
				
				foreach($xml as $key => $value){
					
					if( ($key != "eprintid") && ($key != "rev_number") && ($key != "eprint_status") && ($key != "userid") && ($key != "dir") && ($key != "datestamp") && ($key != "lastmod") && ($key != "status_changed") && ($key != "type") && ($key != "metadata_visibility") && ($key != "latitude") && ($key != "longitude") && ($key != "item_issues_count") && ($key != "title") && ($key != "full_text_status") && ($key != "abstract") && ($key != "collection") && ($key != "copyright_holders") && ($key != "country") && ($key != "state_province") && ($key != "location") && ($key != "geo_location") && ($key != "documents") && ((string)$value != "") ) {
					
					
						$tmp = array(
										"title"	=> str_ireplace("_", " ", ucfirst($key)),
										"value"	=> $value
						);
						
						array_push($item["extra"], $tmp);
					
					}


 
					
				}
				
				
				
	// TO DO
				
				
				// Format of Original
				$item["format_of_original"] = (string)$xml->format_of_original;

				// Original reference
				$item["original_reference"] = (string)$xml->original_reference;
				
				// Copy taken by
				$item["copy_taken_by"] = (string)$xml->copy_taken_by;
				
				// Date of Copy
				$item["date_of_copy"] = date('d F Y', strtotime((string)$xml->date_of_copy));
				
				// License
				$item["license"] = (string)$xml->documents->document->license;
				
				// Catalogue reference
				$item["catalogue_reference"] = (string)$xml->catalogue_reference; 
								
				// Ethnic group
				$item["ethnic_group"] = (string)$xml->ethnic_group; 
				
				// For citation use
				$item["for_citation_use"] = (string)$xml->for_citation_use;
				
				
				// Collection info
				$item["collection"] = self::get_collections((string)$xml->collection);
				

				return $item;
			
			}
		
		}
		return false;
	
	}


	/* 	get single image comments */
	public static function get_image_comments($id, $offset=0, $limit=5) {
	
		$id = (int)$id;	// prevent hacking
		
		// calculate limits
		$min = $offset * $limit;
		$max = $min + $limit;		
		
		$ch = parent::init();

		curl_setopt ($ch, CURLOPT_URL, HTTP."/cgi/comment/$id/EPrint/Serve?format=XML");
		$result = curl_exec($ch);
		
		// No comments or no image
		if( (substr_count($result, "No comments defined") > 0) || (substr_count($result, "Eprint not found using id") > 0) || ($result == "") ){
			return false;
		}
		
		$xml = new SimpleXMLElement(trim($result));
		
		// comments
		$comments = $xml->xpath("//sneep_comment_output/sneep_comments/sneep_comment");

		if( ($comments !== false) && (count($comments) > $min) ) {		
		
			// eventually fix max
			if(count($comments) < $max) {
				$max = count($comments);
			}		
		
			$items = array();
		
			$i = 0;
			foreach($comments as $comment) {

				if( ($i>=$min) && ($i < $max)) {
				
					// get commenter data
					$owner = $comment->xpath("owner_desc");
				
					$attr = $comment->attributes();
					
					$item = array(
									"comment_id"	=> (string)$attr["commentid"],
									"user_id" 		=> (string)$attr["ownerid"],
									"user_name"		=> (string)$owner[0]->span->span[0],
									"creation_date" => (string)$attr["created"],
									"last_mod_date" => (string)$attr["lastmod"],
									"text"			=> (string)$comment[0],
									"total"			=> count($comments)
					);
					
					array_push($items, $item);
					
				}
				
				$i++;
			
			}
			
			return $items;
		
		}
		
		
		return false;
	
	}


	/* 	write single image comments */
	public static function add_image_comment($id, User $user, $post_data, $required, $code) {
	
		$id = (int)$id;	// prevent hacking
		
		// Since ePrints doesn't check if the textarea is empty
		// I check it here
		if($post_data[$required] == "") {
			$user->error = Content::ERROR_TEXT;
			return false;
		}
		
		return $user->write_comment($id, $post_data, $code);		
		
	}

	/* 	delete single image comments */
	public static function delete_image_comment(User $user, $post_data) {
	
		return $user->update_comment($post_data);		
		
	}

	/* 	update single image comments */
	public static function update_image_comment(User $user, $post_data) {
	
		return $user->update_comment($post_data);		
		
	}	
	
	/* related images functions */
	public static function get_image_related($id, $offset=0, $limit=5, $order=null) {
		$id = (int)$id;	// prevent hacking
		
		// calculate limits
		$min = $offset * $limit;
		$max = $min + $limit;		
		
		// set default order
		if(is_null($order) || ($order == "")) {
			$order = urlencode("title/-date_of_original_from");
		} else {
			$order = urlencode($order);
		}
		
		$ch = parent::init();

		curl_setopt ($ch, CURLOPT_URL, HTTP."/cgi/related_items?eprintid=".$id."&p=$limit&s=$min&order=".$order);
				
		$result = curl_exec($ch);
		
		$xml = new SimpleXMLElement(trim($result));
		
		// comments
		$images = $xml->xpath("//item");

		if( ($images !== false) && (count($images) > $min) ) {		
		
			// eventually fix max
			if(count($images) < $max) {
				$max = count($images);
			}		
		
			$items = array();
		
			$i = 0;
			foreach($images as $image) {
			
				if( ($i>=$min) && ($i < $max)) {
									
					$item = $image->xpath("media:content");
					$attr = $item[0]->attributes();
					$img = (string)$attr["url"]; 	
								
					$item = $image->xpath("media:thumbnail");
					$attr = $item[0]->attributes();
					$thumb = (string)$attr["url"]; 	
					
					$img_id = str_replace(HTTP."/", "", (string)$image->guid);
					$img_id = (int)substr($img_id, 0, strlen($img_id)-1);
			
									
					$item = array(
									"id"			=> $img_id,
									"creation_date" => (string)$image->pubDate,
									"title"			=> (string)$image->title,
									"description"	=> (string)$image->description,
									"image"			=> (string)$img,
									"thumb"			=> (string)$thumb,
									"total"			=> count($images)
					);
										
					array_push($items, $item);
					
				}
				
				$i++;
			
			}
			
			return $items;
		
		}
		
		
		return false;
	
	}

	
	/* search functions */
	public static function simple_search($q=null, $collection_id=null, $offset=0, $limit=5, $isCollection = false, $order = null) {
	
		// set default order
		if(is_null($order) || ($order == "")) {
			$order = urlencode("title/-date_of_original_from");
		} else {
			$order = urlencode($order);
		}
	
		// calculate limits
		$min = $offset * $limit;
		$max = $min + $limit;
		
		$total_items = $max;
	
		$ch = parent::init();
		
		if($isCollection) {
			// get total items
			if( ($total_items = self::get_total_items(HTTP."/cgi/search/advanced?screen=Public%3A%3AEPrintSearch&type=image&order=$order&collection=".urlencode($collection_id))) === false)
				return false;
							
			// get ONLY the items I need
			curl_setopt ($ch, CURLOPT_URL, HTTP."/cgi/search/advanced?screen=Public%3A%3AEPrintSearch&_action_export=1&output=RSS2&type=image&order=$order&collection=".urlencode($collection_id)."&p=$limit&s=$min"); 
						//echo HTTP."/cgi/search/advanced?screen=Public%3A%3AEPrintSearch&_action_export=1&output=RSS2&type=image&order=$order&collection=".urlencode($collection_id)."&p=$limit&s=$min";
		} else {

			// collection info (if needed)
			$collection = "";
			if( (!is_null($collection_id)) && ($collection_id != "") ) {
				$collection = "&collection=".urlencode($collection_id);
			}
			// get total items
			if( ($total_items = self::get_total_items(HTTP."/cgi/search/advanced?screen=Public%3A%3AEPrintSearch&type=image&order=$order&q=".urlencode($q).$collection)) === false)
				return false;
			
			// get ONLY the items I need
			curl_setopt ($ch, CURLOPT_URL, HTTP."/cgi/search/advanced?screen=Public%3A%3AEPrintSearch&_action_export=1&output=RSS2&type=image&order=$order&q=".urlencode($q).$collection."&p=$limit&s=$min");
			
		}
		
		$result = curl_exec($ch);
				
		$xml = new SimpleXMLElement($result);
		
		// Collection Title
		$collection_title = $xml->xpath("//rss/channel/title");
		$tmp = explode('"', (string)$collection_title[0]);
		$collection_title = $tmp[1];	
			
		// items
		$items = $xml->xpath("//rss/channel/item");
			
		// search results
		$results = array();


		//for($i=$min; $i < $max; $i++) {
		for($i=0; $i < count($items); $i++) {
			
			// get title
			$tmp = array();
			$item = $items[$i]->xpath("title");
			$tmp["title"] = (string)$item[0];  
			
			// get img thumb
			$item = $items[$i]->xpath("media:thumbnail");
			if($item) {
				$attr = $item[0]->attributes();
				$tmp["img"] = (string)$attr["url"];  
				
				// get link and extract the ID
				$item = $items[$i]->xpath("link");
				$link = str_replace(HTTP, "", (string)$item[0]);
				$tmp["id"] = str_replace("/", "", $link);			
				
				array_push($results, $tmp);
			}
		}

		return array(
						"items"	=> $results,
						"total"	=> $total_items,
						"title"	=> $collection_title
					);	

		return false;
	}
	public static function search_by_id($id, $more=false) {
	
		$id = (int)$id;	// prevent hacking
	
		$ch = parent::init();
		
		curl_setopt ($ch, CURLOPT_URL, HTTP."/cgi/search/advanced?screen=Public%3A%3AEPrintSearch&_action_export=1&output=RSS2&type=image&eprintid=$id");
		$result = curl_exec($ch);
		
		$xml = new SimpleXMLElement($result);
				
		// items
		$items = $xml->xpath("//rss/channel/item");
				
		if(( count($items) == 1) && ($items !== false)) {
		
			// get title
			$image = array();
			$item = $items[0]->xpath("title");
			$image["title"] = (string)$item[0];  
			
			// get img thumb
			$item = $items[0]->xpath("media:thumbnail");
			$attr = $item[0]->attributes();
			$image["thumb"] = (string)$attr["url"];    
			
			// get small img
			$item = $items[0]->xpath("media:content");
			$attr = $item[0]->attributes();
			$image["img"] = (string)$attr["url"];    
			
			// if required get also description and pubDate
			if($more) {
				$item = $items[0]->xpath("description");
				$image["description"] = (string)$item[0];  
				
				$item = $items[0]->xpath("pubDate");
				$image["date"] = date('d F Y', strtotime((string)$item[0])); 
				
			}
		
			
			return $image;
				
		}
	
		return false;
	}
	// get search URL
	public static function get_search_url($q=null, $collection_id=null, $isCollection = false, $order = null) {
	
		// set default order
		if(is_null($order) || ($order == "")) {
			$order = urlencode("title/-date_of_original_from");
		} else {
			$order = urlencode($order);
		}
			
		if($isCollection) {	
			return HTTP."/cgi/search/advanced?screen=Public%3A%3AEPrintSearch&type=image&order=$order&collection=".urlencode($collection_id);
						
		} else {

			// collection info (if needed)
			$collection = "";
			if( (!is_null($collection_id)) && ($collection_id != "") ) {
				$collection = "&collection=".urlencode($collection_id);
			}
			return HTTP."/cgi/search/advanced?screen=Public%3A%3AEPrintSearch&type=image&order=$order&q=".urlencode($q).$collection;
			
		}

	}
	
	/* get the total amount of items in search and browse collections */ 
	public static function get_total_items($url) {
	
		$ch = parent::init();
		
		curl_setopt ($ch, CURLOPT_URL, $url);
		$result = curl_exec($ch);
		
		$xml = new SimpleXMLElement($result);
				
		// items
		$items = $xml->xpath("//div[@id='search_results']/div[@class='title']/h2");
		
		if( ($items !== false) && (count($items) > 0)) {
		
			$matches = array();
			if ( preg_match("/returned +[0-9]+ matches/i", $items[0], $matches ) )
				return str_ireplace("returned ", "", str_ireplace(" matches", "", $matches[0]));
			
		}
		
		return false;
	
	}



}